"use strict"
var areaSelect = function(objs){
  console.info(objs);
  // 加载一个下拉框的数据
  let loadData = function(obj,pid){
    if($(obj).length==0){
    	return new Promise(function(success,fail){});
    }
    return new Promise(function(success,fail){
      $.post(
        "areas.let?pid="+pid,
        function(data){
          obj.children(":not(:eq(0))").remove();
          for(let item of data){
            obj.append(new Option(item.name,item.id));
          }
          success(obj,data);
        },"json"
      );
    });
  }
  
  
  
  objs.on("change",function(){
	  let pid = $(this).val();
	  let obj = $(this).next();
	  if(pid==""){
		  obj.children(":not(:eq(0))").remove();
		  obj.trigger("change");
		  return ;
	  }
	  loadData(obj,pid).then(function(){
		  obj.trigger("change");
	  });
  });
  
  
  // 如果是修改呢？
  let id = objs.eq(4).data("id");
  if(id!=null){
	  $.post(
        "areas.let?action=list&id="+id,
        function(data){
        	loadData(objs.eq(0),0).then((obj)=>{
        		obj.val(data[0].id);
        	});
        	for(let i=1;i<data.length;i++){
        		loadData(objs.eq(i),data[i-1].id).then((obj)=>{
            		obj.val(data[i].id);
            	});
        	}
        },"json"
      ); 
  }else{
	  loadData(objs.eq(0),0);
  }
}

//$("._areaSelect").each(function(){
//  areaSelect($(this).children());
//});

areaSelect($("._areaSelect:eq(0)").children());

var list = $("._list");
var template = list.children().remove();
var loadAddress = function(){
	list.empty();
	$.post(
			"mall-address.let",
			function(data){
				console.info(data);
				for(let item of data.data){
					let obj = template.clone();
					list.append(obj);
					for(let name in item){
						console.info(name);
						obj.find('[name="'+name+'"]').val(item[name]);
					}
					obj.find('[name="addressDefault"]').prop("checked",item.addressDefault).val(true);
					obj.find("._areaSelect").children().eq(4).data("id",item.addressCode);
					areaSelect(obj.find("._areaSelect").children());
				}
			},"json"
	);
}
loadAddress();

$("body").on("submit","form",function(){
	$.post(
			"user/mall-address.let",
			sys.form.param(this).toString(),
			function(data){
				if(data.code==200){
					sys.toastr.success("操作成功");
					loadAddress();
				}else{
					sys.toastr.error(data.message);
				}
			},"json"
	);
	
	return false;
}).on("click","._del",function(){
	let addressId = new FormData(this.form).get("addressId");
	console.info(addressId);
	$.post(
			"user/mall-address.let?action=delete&addressId="+addressId,
			function(data){
				if(data.code==200){
					sys.toastr.success("删除成功");
					window.location.reload();
				}else{
					sys.toastr.error(data.message);
				}
			},"json"
	);
	
	
});






